package com.util.vmwareops;

import com.vmware.vim25.CustomFieldStringValue;
import com.vmware.vim25.CustomFieldValue;
import com.vmware.vim25.mo.Network;
import com.vmware.vim25.mo.VirtualMachine;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class VirtualMachineOps {
    public synchronized static List<VMInfo> updateVM(Connection con, HostInfo host, VirtualMachine[] vms, String versionId) throws SQLException {
        System.out.println(String.format("[INFO] Update VM start"));

        List<VMInfo> vmInfo = new ArrayList<VMInfo>();
        Statement stmt = null;
        stmt = con.createStatement();

        for(VirtualMachine vm : vms) {
            // 获取端口组字符串
            String networkStr = "";
            try {
                Network[] net = vm.getNetworks();
                for (Network n : net) {
                    networkStr += n.getName() + "\n";
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            // 获取自定义属性
            String prop = "";
            if(vm.getCustomValue() != null) {
                for (CustomFieldValue cusfield : vm.getCustomValue()) {
                    CustomFieldStringValue name = (CustomFieldStringValue) cusfield;
                    prop += name.getValue() + "\n";
                }
            }

            VMInfo tmp = new VMInfo(
                    MyUtils.getUUID("VM"),
                    vm.getConfig().uuid,
                    host,
                    vm.getName(),
                    vm.getGuest().hostName,
                    vm.getGuest().ipAddress,
                    networkStr,
                    vm.getRuntime().powerState.toString(),
                    vm.getRuntime().connectionState.toString(),
                    vm.getConfig().hardware.numCPU,
                    vm.getConfig().hardware.memoryMB / 1024.0,
                    vm.getSummary().storage.uncommitted / 1024.0 / 1024.0 / 1024.0,
                    prop,
                    "",
                    versionId
            );

            vmInfo.add(tmp);
            String sql_command = String.format(
                    "insert into resource_bundle_vsphere_vm values(\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %d, %.2f, %.2f,  \"%s\", \"%s\", \"%s\")",
                    tmp.getId(),
                    tmp.getUuid(),
                    tmp.getHost().getId(),
                    tmp.getName(),
                    tmp.getHostname(),
                    tmp.getIpAddress(),
                    tmp.getNetwork(),
                    tmp.getPowerState(),
                    tmp.getConnectState(),
                    tmp.getCpu(),
                    tmp.getMem(),
                    tmp.getStorage(),
                    tmp.getCIName(),
                    tmp.getCIAppname(),
                    tmp.getVersionId()
            );
            // System.out.println(sql_command);
            stmt.execute(sql_command);
        }

        System.out.println(String.format("[INFO] Update VM end"));
        return vmInfo;
    }

    public static List<VMInfo> getVMInfoByVersionId(String versionId, Map<String, HostInfo> hostInfos) throws InterruptedException {
        DBConnectionPool db = DBConnectionPoolFactory.getDBConnectionPool("vmwareops");
        Connection con = db.getConnection();
        List<VMInfo> vmInfos = new ArrayList<VMInfo>();
        String sql = String.format("select * from %s where version=\'%s\'", "resource_bundle_vsphere_vm", versionId);
        System.out.println(sql);
        try {
            Statement stmt = con.createStatement();
            ResultSet res = stmt.executeQuery(sql);
            if(res == null) {
                return null;
            }
            while(res.next()) {
                vmInfos.add(
                        new VMInfo(
                                res.getString("id"),
                                res.getString("vm_id"),
                                hostInfos.get(res.getString("resource_host_id")),
                                res.getString("vm_name"),
                                res.getString("guest_hostname"),
                                res.getString("addresses"),
                                res.getString("network"),
                                res.getString("power_state"),
                                res.getString("connect_state"),
                                res.getInt("cpu"),
                                res.getDouble("memory_in_gb"),
                                res.getDouble("total_storage_in_gb"),
                                res.getString("CI_name"),
                                "",
                                res.getString("version")
                        )
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(con != null) {
                db.close(con);
            }
        }
        return vmInfos;
    }
}
